package com.liulu.tools

import android.app.Activity
import android.graphics.Point
import android.graphics.Rect
import android.os.Build
import android.view.WindowInsets
import androidx.window.layout.WindowMetricsCalculator

/**
 * 获取屏幕尺寸（全屏）
 */
val Activity?.screenSizePoint: Point
    @JvmName("screenSizePoint")
    get() {
        val windowManager = this?.windowManager
        windowManager ?: return Point()
        // 兼容旧版本（需判断 API Level）
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val windowMetrics = windowManager.currentWindowMetrics
            val size = Point()
            size.x = windowMetrics.bounds.width()
            size.y = windowMetrics.bounds.height()
            size
        } else {
            val display = windowManager.defaultDisplay
            val size = Point()
            display.getRealSize(size)
            size
        }
    }

/**
 * 获取屏幕尺寸（全屏）
 */
val Activity?.screenSizeRect: Rect
    @JvmName("screenSizeRect")
    get() {
        this ?: return Rect()
        return WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(this).bounds
    }

/**
 * 获取屏幕宽度
 */
val Activity?.screenWidth: Int
    get() {
        this ?: return 0
        return WindowMetricsCalculator.getOrCreate()
            .computeCurrentWindowMetrics(this).bounds.width()
    }

/**
 * 获取屏幕高度
 */
val Activity?.screenHeight: Int
    get() {
        this ?: return 0
        return WindowMetricsCalculator.getOrCreate()
            .computeCurrentWindowMetrics(this).bounds.height()
    }


/**
 * 获取屏幕尺寸（排除状态栏/导航栏）
 */
val Activity?.appScreenSizePoint: Point
    @JvmName("appScreenSizePoint")
    get() {
        val windowManager = this?.windowManager
        windowManager ?: return Point()
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 通过 WindowMetrics 获取可用区域（推荐）
            val windowMetrics = windowManager.currentWindowMetrics
            val insets =
                windowMetrics.windowInsets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
            val size = Point()
            size.x = windowMetrics.bounds.width() - insets.left - insets.right
            size.y = windowMetrics.bounds.height() - insets.top - insets.bottom
            size
        } else {
            val display = windowManager.defaultDisplay
            val size = Point()
            display.getSize(size)
            size
        }
    }